import {
    createRouter,
    createWebHashHistory,
    type NavigationGuardNext,
    type RouteComponent,
    type RouteLocationNormalized,
    type RouteLocationNormalizedLoaded,
    type RouteRecordRaw,
    type RouteRecordSingleView
} from "vue-router";
import {basicRouter} from "./basic.ts";
import type {App} from "vue";
import {useAuthStore} from "@/store/modules/auth";
import {useAppStore} from "@/store/modules/app";
import progress from "nprogress";
import "nprogress/nprogress.css";
import type {SysPermission} from "@/typings/sys";

const modules = import.meta.glob('@/views/**/index.vue');

declare module 'vue-router' {
    interface RouteMeta {
        title: string
        icon?: string
        iconColor?: string
    }
}

progress.configure({
    showSpinner: false
})

export const router = createRouter({
    history: createWebHashHistory(),
    routes: basicRouter
})


const loadView = (view: string): RouteComponent => {
    const tmp = "/src/views/" + view + "/index.vue";
    for (const path in modules) {
        if (path === tmp) {
            return modules[path];
        }
    }
    // 匹配不到则返回异常路径
    return () => import("@/views/error/index.vue");
};

const filterRoute = (data: Array<SysPermission>) => {
    let routerList: Array<RouteRecordRaw> = [];
    data.forEach((item: SysPermission) => {
        if (item.children && item.children.length > 0) {
            routerList = routerList.concat(filterRoute(item.children));
        } else {
            if (item.permissionView) {
                const routeItem: RouteRecordSingleView = {
                    path: item.permissionPath ?? "",
                    name: item.permissionName ?? "",
                    component: loadView(item.permissionView ?? ""),
                    meta: {
                        title: item.permissionTitle,
                        icon: item.permissionIcon,
                        iconColor: item.permissionIconColor
                    }
                }
                routerList.push(routeItem)
            }

        }
    });
    return routerList;
};

export const addRouter = () => {
    const authStore = useAuthStore();
    if (authStore.loadRouter) {
        return;
    }
    // 加载路由
    const dynamicRoutes = filterRoute(authStore.permissions);
    dynamicRoutes.forEach((item) => {
        router.addRoute('home', item);
    })
    authStore.loadRouter = true;
}

const goNext = (to: RouteLocationNormalized, next: NavigationGuardNext) => {
    const appStore = useAppStore();
    const authStore = useAuthStore();
    if (!authStore.loadRouter) {
        // 加载路由
        addRouter();
        next({...to, replace: true})
    } else {
        // 已加载路由后则直接跳转
        const title = to.meta.title;
        document.title = title + " - " + appStore.systemName;
        next();
    }
}

export async function setupRouter(app: App) {
    addRouter();
    app.use(router);

    // @ts-ignore
    router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded, next: NavigationGuardNext) => {
        progress.start();
        const authStore = useAuthStore();
        if (to.path !== "/login") {
            // 如果未登录，则跳转登录页
            if (!authStore.isLogin) {
                next("/login");
            } else {
                goNext(to, next);
            }
        } else {
            // 如果已登录，直接跳转首页
            if (authStore.isLogin) {
                next("/");
            } else {
                const appStore = useAppStore();
                // 已加载路由后则直接跳转
                const title = to.meta.title;
                document.title = title + " - " + appStore.systemName;
                next();
            }
        }
        return true;
    });
    router.afterEach(async () => {
        progress.done();
        return true;
    });

    await router.isReady();
}